#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const int MAXN = 100005;

// 定义链表节点结构体
struct Node {
    int address;
    int data;
    int next;
};

// 读取链表
vector<Node> readList(int head, Node nodes[]) {
    vector<Node> list;
    for (int p = head; p != -1; p = nodes[p].next) {
        list.push_back(nodes[p]);
    }
    return list;
}

// 反转链表
void reverseList(vector<Node>& list) {
    reverse(list.begin(), list.end());
}

// 合并链表
vector<Node> mergeLists(const vector<Node>& longList, const vector<Node>& shortList) {
    vector<Node> result;
    int i = 0, j = 0;
    int k = 0;
    while (i < longList.size()) {
        result.push_back(longList[i++]);
        if (i < longList.size()) {
            result.push_back(longList[i++]);
        }
        if (j < shortList.size()) {
            result.push_back(shortList[j++]);
        }
    }
    return result;
}

int main() {
    int head1, head2, N;
    cin >> head1 >> head2 >> N;

    Node nodes[MAXN];
    for (int i = 0; i < N; ++i) {
        int address, data, next;
        cin >> address >> data >> next;
        nodes[address] = {address, data, next};
    }

    vector<Node> list1 = readList(head1, nodes);
    vector<Node> list2 = readList(head2, nodes);

    vector<Node> longList, shortList;
    if (list1.size() >= 2 * list2.size()) {
        longList = list1;
        shortList = list2;
    } else {
        longList = list2;
        shortList = list1;
    }

    reverseList(shortList);
    vector<Node> mergedList = mergeLists(longList, shortList);

    for (int i = 0; i < mergedList.size(); ++i) {
        if (i < mergedList.size() - 1) {
            printf("%05d %d %05d\n", mergedList[i].address, mergedList[i].data, mergedList[i + 1].address);
        } else {
            printf("%05d %d -1\n", mergedList[i].address, mergedList[i].data);
        }
    }

    return 0;
}    